﻿using System;
using System.Linq;
using System.Windows;
using LINQPad.OpenAccess.Helpers;
using LINQPad.OpenAccess.Infrastructure;
using LINQPad.OpenAccess.UI.ViewModel;

namespace LINQPad.OpenAccess.UI.Services
{
    /// <summary>
    /// <see cref="IConnectionSettingsViewFactory"/>
    /// </summary>
    public class ConnectionSettingsViewFactory : IConnectionSettingsViewFactory
    {
        private readonly IServiceLocator _serviceLocator;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionSettingsViewFactory" /> class.
        /// </summary>
        /// <param name="serviceLocator">The service locator.</param>
        public ConnectionSettingsViewFactory( IServiceLocator serviceLocator )
        {
            Guard.ArgumentNotNull( serviceLocator, "serviceLocator" );

            this._serviceLocator = serviceLocator;
        }

        #region IConnectionSettingsViewFactory Members

        /// <summary>
        /// Creates the connection settings view for the specified view model.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <returns>
        /// The view or <c>null</c>.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public FrameworkElement CreateConnectionSettingsView( IConnectionSettingsViewModel viewModel )
        {
            if ( viewModel == null )
                return null;

            // TODO: renice me
            var viewModelType = viewModel.GetType( );
            var viewFullTypeName = viewModelType.FullName.Replace( "ViewModel", "View" );
            var viewType = Type.GetType( viewFullTypeName, throwOnError: false );
            if ( viewType == null )
                return null;

            return this._serviceLocator.TryGet( viewType ) as FrameworkElement;
        }

        #endregion
    }
}
